package com.hxd.otc.module.wallet.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.wallet.bean.PayOrderResultBean;
import com.hxd.otc.module.wallet.bean.WalletFeeRuleBean;
import com.hxd.otc.module.wallet.bean.WalletOrderInfoBean;
import com.hxd.otc.module.wallet.contract.WalletAECPayConfirmContract;
import com.hxd.otc.module.wallet.presenter.AECPayConfirmPresenter;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.ConvertUtil;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.WalletCoinTypes;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.LimitNumberTextWatcher;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.WalletDialogTipsUtil;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/8 10:33
 * 描  述 :  付款确认页面
 */
public class WalletPayConfirmActivity extends BaseActivity<AECPayConfirmPresenter> implements WalletAECPayConfirmContract.View {


    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_address_has_number)
    TextView tvaddressHasNumber;
    @BindView(R.id.tv_address_no_number)
    TextView tvaddressnONumber;
    @BindView(R.id.et_pay_number)
    EditText etPayNumber;
    @BindView(R.id.et_trade_pw)
    EditText etTradePw;
    @BindView(R.id.et_sms_code)
    EditText etSmsCode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.btn_change)
    Button btnPay;
    @BindView(R.id.ll_has_number)
    LinearLayout llHasNumber;
    @BindView(R.id.ll_no_number)
    LinearLayout llNoNumber;
    @BindView(R.id.ll_pay_number)
    LinearLayout llPayNumber;
    @BindView(R.id.tv_number_tips)
    TextView tvNumberTips;
    @BindView(R.id.tv_address_tips)
    TextView tvAddressTips;
    @BindView(R.id.iv_see_hide)
    ImageView ivSeeHide;
    @BindView(R.id.fl_see_hide)
    FrameLayout flSeeHide;
    @BindView(R.id.rl_sms)
    RelativeLayout rlSms;
    //无金额类型
    public static final int PAY_TYPE_NORMAL = 1;
    //商户订单类型
    public static final int PAY_TYPE_MERCHANTS = 2;
    //API支付类型
    public static final int PAY_TYPE_API_PAY = 3;

    @BindView(R.id.v_pay_number_line)
    View vPayNumberLine;
    @BindView(R.id.v_tpw_line)
    View vTpwLine;
    @BindView(R.id.view_send_code_line)
    View viewSendCodeLine;
    @BindView(R.id.rl_fee)
    RelativeLayout rlFee;
    @BindView(R.id.tv_handling_fee)
    TextView tvHandlingFee;
    @BindView(R.id.tv_actual_arrival)
    TextView tvActualArrival;
    @BindView(R.id.tv_tip_aec)
    TextView tvTipAec;
    @BindView(R.id.ll_tip_aec)
    LinearLayout llTipAec;
    @BindView(R.id.tv_save_tips)
    TextView tvSaveTip;
    @BindView(R.id.tv_save_tips_content)
    TextView tvSaveTipsContent;

    private boolean isShowPsw;

    private static final String AEC = "AEC";
    private static final String MSC = "MSC";

    private WalletOrderInfoBean mOrderInfo;

    //地址
    private String mAddress = "";

    //转币数量
    private double coinNums = 0;

    //转币类型
    private String coinType = "";

    //钱包首页传递进来
    List<WalletFeeRuleBean> feeRuleBeans;

    private int mPayType;//支付类型

    public static final String EXTRA_PAY_TYPE = "type";
    public static final String EXTRA_ORDER_INFO = "order_info";
    public static final String EXTRA_ADDRESS = "address";
    private PayOrderResultBean mPayOrderResultBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_aec_confirm;
    }

    @Override
    protected void initView() {
        rlSms.setVisibility(View.GONE);
        mPayType = getBundle().getInt(EXTRA_PAY_TYPE);

        switch (mPayType) {
            case PAY_TYPE_MERCHANTS:
                initViewOfMerchantsOrder();
                break;
            case PAY_TYPE_API_PAY:
                initViewOfApiPayOrder();
                break;
            case PAY_TYPE_NORMAL:
            default:
                initViewOfNormalPay();
                break;
        }
    }

    private void initViewOfNormalPay() {
        titleBar.setTitleText(getString(R.string.wallet_pay_confirm_aec_title));
        mAddress = (String) getBundle().get(EXTRA_ADDRESS);
        if (TextUtils.isEmpty(mAddress)) {
            showToast(getString(R.string.wallet_toast_change_coin_aec_address_error));
            finish();
        }
        calculation();
        mPresenter.bringCoinFeeRule();
        tvaddressnONumber.setText(mAddress);
        coinType = "AEC";
        llHasNumber.setVisibility(View.GONE);
        llNoNumber.setVisibility(View.VISIBLE);
        llPayNumber.setVisibility(View.VISIBLE);
        llTipAec.setVisibility(View.VISIBLE);
        //ui线
        vTpwLine.setVisibility(View.VISIBLE);
        viewSendCodeLine.setVisibility(View.GONE);
        tvTipAec.setText(Html.fromHtml(getString(R.string.wallet_save_tips3
                , getString(R.string.transer_zero)
                , getString(R.string.transer_zero)
                , getString(R.string.aec)
                , getString(R.string.transer_zero)
                , getString(R.string.aec)
        )));
    }

    private void initViewOfMerchantsOrder() {
        mOrderInfo = (WalletOrderInfoBean) getBundle().getSerializable(EXTRA_ORDER_INFO);
        if (mOrderInfo != null) {
            mAddress = mOrderInfo.getAddress();
            coinNums = mOrderInfo.getAmount();
            coinType = mOrderInfo.getCoinType();//支持AEC、MSC
            if (coinType.equals(AEC)) {
                titleBar.setTitleText(getString(R.string.wallet_pay_confirm_aec_title));
                tvNumberTips.setText(getString(R.string.wallet_text_pay_nums_aec));
                tvNumber.setText(coinNums + "");
                tvAddressTips.setText(getString(R.string.wallet_pay_address_aec_tips));
                tvaddressHasNumber.setText(mAddress);
            } else if (coinType.equals(MSC)) {
                titleBar.setTitleText(getString(R.string.wallet_pay_confirm_msc_title));
                tvNumberTips.setText(getString(R.string.wallet_text_pay_nums_msc));
                tvNumber.setText(coinNums + "");
                tvAddressTips.setText(getString(R.string.wallet_pay_address_msc_tips));
                tvaddressHasNumber.setText(mAddress);
            }
            llHasNumber.setVisibility(View.VISIBLE);
            llNoNumber.setVisibility(View.GONE);
            llPayNumber.setVisibility(View.GONE);
            //ui线
            vTpwLine.setVisibility(View.GONE);
            viewSendCodeLine.setVisibility(View.VISIBLE);
        } else {
            showToast(getString(R.string.wallet_toast_change_coin_aec_address_error));
            finish();
        }
    }

    private void initViewOfApiPayOrder() {
        mPayOrderResultBean = (PayOrderResultBean) getBundle().getSerializable(EXTRA_ORDER_INFO);
        if (mPayOrderResultBean == null) {
            showToast(getString(R.string.walllet_failed_to_get_payment_order_information));
            return;
        }
        String coinType = mPayOrderResultBean.getCoinType();
        titleBar.setTitleText(String.format(getString(R.string.wallet_coin_payment), coinType));
        tvNumberTips.setText(String.format(getString(R.string.wallet_coin_payment_nums), coinType));
        tvNumber.setText(String.format("%s", mPayOrderResultBean.getAmountCoin()));
        tvAddressTips.setText(String.format(getString(R.string.wallet_pay_address_coin_tips), coinType));
        tvaddressHasNumber.setText(mPayOrderResultBean.getToAddress());

        tvSaveTip.setVisibility(View.GONE);
        tvSaveTipsContent.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        etPayNumber.addTextChangedListener(new LimitNumberTextWatcher(etPayNumber, 9, 8));
        //没设置交易密码点击edittext弹出对话框
        etTradePw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                /*return true不会响应键盘打开事件，但是有响应触摸事件
                也就是说在响应触摸按下和松开后，事件就被消费而不往下传递了
                return false时，在触摸被松开的时候响应打开键盘事件，
                如果触摸长时间被按下，触摸松开时也不会对其他时间进行相应
                例如，不会打开系统默认键盘。
                */
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (!UserHelper.isSetPayPassword()) {
                            WalletDialogTipsUtil.showTpwTipsDialog(WalletPayConfirmActivity.this);
                        }
                        break;
                }
                return false;
            }
        });

        etPayNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                calculation();
            }
        });
        flSeeHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowPsw = !isShowPsw;
                if (isShowPsw) {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_according_icon);
                    etTradePw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_hidden_icon);
                    etTradePw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                if (!TextUtils.isEmpty(etTradePw.getText())) {
                    etTradePw.setSelection(etTradePw.getText().length());
                }
            }
        });
        //发送验证码
        tvSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getSmsCode(UserHelper.getNationalCode(), UserHelper.getMobile(), "3");
            }
        });
        //确定付款
        btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDataAndPay();
            }
        });

        //默认不显示密码
        isShowPsw = true;
        flSeeHide.performClick();

    }

    @Override
    protected AECPayConfirmPresenter createPresenter() {
        return new AECPayConfirmPresenter(this);
    }

    private void checkDataAndPay() {

        switch (mPayType) {
            case PAY_TYPE_MERCHANTS:
                checkDataOfMerchantsOrder();
                break;
            case PAY_TYPE_API_PAY:
                checkDataOfApiPayOrder();
                break;
            case PAY_TYPE_NORMAL:
            default:
                checkDataOfNormal();
                break;
        }
    }

    private void checkDataOfApiPayOrder() {
        String payPassword = etTradePw.getText().toString().trim();
        if (!DataUtils.isPayPassword(payPassword)) {
            return;
        }
        onShowLoading();
        mPresenter.innerPayOrder(payPassword, mPayOrderResultBean.getPreId());
    }

    private void checkDataOfMerchantsOrder() {
        if (coinType.equals(AEC)) {
            String tpw = etTradePw.getText().toString().trim();
            String verify_code = etSmsCode.getText().toString().trim();
            if (coinNums == 0) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_nums);
                return;
            }
            if (TextUtils.isEmpty(mAddress)) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_address);
                return;
            }
            if (TextUtils.isEmpty(tpw)) {
                BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_tpw);
                return;
            }
            //最大值之间
            if (coinNums > WalletCoinTypes.getInstance().getBalance(getString(R.string.aec))) {
                BlocksToast.get().showToast(R.string.wallet_toast_change_coin_aec_not_enough_nums);
                return;
            }
            String from_address;
            try {
                from_address = WalletCoinTypes.getInstance().getAddress(getString(R.string.aec));
            } catch (Exception e) {
                from_address = "";
            }
            if (TextUtils.isEmpty(from_address)) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_aec_address_error);
                return;
            }
            if (mOrderInfo != null)
                mPresenter.coinTransfer(coinNums + "", verify_code, coinType, from_address, tpw, mOrderInfo.getOrderId(), "1", mAddress);
        } else if (coinType.equals(MSC)) {
            String tpw = etTradePw.getText().toString().trim();
            String verify_code = etSmsCode.getText().toString().trim();
            if (coinNums == 0) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_nums);
                return;
            }
            if (TextUtils.isEmpty(mAddress)) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_address);
                return;
            }
            if (TextUtils.isEmpty(tpw)) {
                BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_tpw);
                return;
            }
            //最大值之间
            if (coinNums > WalletCoinTypes.getInstance().getBalance(getString(R.string.msc))) {
                BlocksToast.get().showToast(R.string.wallet_toast_change_coin_msc_not_enough_nums);
                return;
            }
            String from_address;
            try {
                from_address = WalletCoinTypes.getInstance().getAddress(getString(R.string.msc));
            } catch (Exception e) {
                from_address = "";
            }
            if (TextUtils.isEmpty(from_address)) {
                BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_msc_address_error);
                return;
            }
            if (mOrderInfo != null)
                mPresenter.coinTransfer(coinNums + "", verify_code, coinType, from_address, tpw, mOrderInfo.getOrderId(), "2", mAddress);
        }
    }

    private void checkDataOfNormal() {
        String nums = etPayNumber.getText().toString().trim();
        String tpw = etTradePw.getText().toString().trim();
        if (TextUtils.isEmpty(nums)) {
            BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_nums);
            return;
        }
        if (TextUtils.isEmpty(mAddress)) {
            BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_empty_address);
            return;
        }
        if (TextUtils.isEmpty(tpw)) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_tpw);
            return;
        }

        //最少和最大值之间
        try {
            double withdraw_aec_num = ConvertUtil.convertToDouble(nums);
            if (withdraw_aec_num > WalletCoinTypes.getInstance().getBalance(getString(R.string.aec))) {
                BlocksToast.get().showToast(R.string.wallet_toast_change_coin_aec_not_enough_nums);
                return;
            }
        } catch (Exception e) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_error_nums);
            return;
        }
        String from_address;
        try {
            from_address = WalletCoinTypes.getInstance().getAddress(getString(R.string.aec));
        } catch (Exception e) {
            from_address = "";
        }
        if (TextUtils.isEmpty(from_address)) {
            BlocksToast.get().showToast(R.string.wallet_toast_pay_confirm_aec_address_error);
            return;
        }
        if (feeRuleBeans == null || feeRuleBeans.size() <= 0) {
            showToast(getString(R.string.net_error));
            return;
        }
        if (Double.valueOf(etPayNumber.getText().toString()) < feeRuleBeans.get(0).minTransferAmount) {
            showToast(getString(R.string.transer_number_hint, feeRuleBeans.get(0).minTransferAmount + ""));
            return;
        }
        mPresenter.coinTransfer(nums, "", coinType, from_address, tpw, "", "0", mAddress);
    }

    //发送验证码成功倒计时
    @Override
    public void SmsSendSuccess() {
        CommonUtil.countdown(60)//开启60秒倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.<Long>bindAutoDispose())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                        tvSendCode.setEnabled(false);
                        tvSendCode.setText(aLong + "s");
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        tvSendCode.setEnabled(true);
                        tvSendCode.setText(R.string.wallet_verify_code_re_send);
                    }
                });
        BlocksToast.get().showToast(R.string.wallet_toast_verify_code_sended);
    }

    @Override
    public void transferSuccess() {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isAECPay", true);
        $startActivity(RemotePaySuccessActivity.class);
        finish();
    }

    @Override
    public void innerPayOrderSuccess(PayOrderResultBean payOrderResultBean) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isAECPay", true);
        $startActivity(RemotePaySuccessActivity.class);
        finish();
    }

    @Override
    public void setSMSEnable(boolean b) {
        tvSendCode.setEnabled(b);
    }

    @Override
    public void setTransferEnable(boolean b) {
        btnPay.setEnabled(b);
    }

    @Override
    public void getbringCoinFeeRule(List<WalletFeeRuleBean> ruleBeans) {
        feeRuleBeans = ruleBeans;
        tvTipAec.setText(Html.fromHtml(getString(R.string.wallet_save_tips3
                , CommonUtil.getPercentage(feeRuleBeans.get(0).inFeePercent)
                , StringUtil.format2Number(feeRuleBeans.get(0).inFeeMinAmount)
                , getString(R.string.aec)
                , StringUtil.format2Number(feeRuleBeans.get(0).inFeeMinAmount)
                , getString(R.string.aec)
        )));
        calculation();
    }


    private void calculation() {

        if (feeRuleBeans == null || feeRuleBeans.size() <= 0 || feeRuleBeans.get(0).inFeeMinAmount <= 0 || TextUtils.isEmpty(etPayNumber.getText().toString().trim())) {
            rlFee.setVisibility(View.GONE);
            return;
        } else {
            rlFee.setVisibility(View.VISIBLE);
        }
        tvHandlingFee.setText(getString(R.string.handling_fee,
                StringUtil.format8Number(Double.valueOf(etPayNumber.getText().toString().trim()) * feeRuleBeans.get(0).inFeePercent),
                getString(R.string.aec)));
        tvActualArrival.setText(getString(R.string.actual_arrival, etPayNumber.getText().toString().trim(), getString(R.string.aec)));
    }

    @Override
    public void onShowLoading() {
        showSpinnerDlg(null, false);
    }

    @Override
    public void onHideLoading() {
        dismissSpinnerDlg();
    }
}